<?php

namespace addons\store\controller;

use addons\store\Store as baseStore;
use addons\store\server\Store as storeServer;
use data\service\Order as OrderService;
use \think\Session as Session;
use data\model\DistrictModel;
use data\service\Config as WebConfig;
use data\service\Upload\AliOss;
use data\model\VslOrderModel;
use data\service\BaseService;
use addons\store\model\VslStoreAssistantModel;
use addons\giftvoucher\server\GiftVoucher as VoucherServer;
use data\service\MemberCard;
use data\extend\WchatOauth;
use addons\groupshopping\server\GroupShopping;
use think\Validate;

/**
 * o2o门店控制器
 * Class GoodHelper
 * @package addons\store\controller
 */
class Wapstore extends baseStore {
    
    public $assistantId;
    
    public $shopId;
    
    public $store_id;//店员选择的店铺id
    
    public $upload_avator;
    
    public $upload_type;
    
    private $return = array();

    public function __construct() {
        parent::__construct();
        $base = new BaseService();
        $model = $base->getRequestModel();
        $website_id = checkUrl();
        if ($website_id && is_numeric($website_id)) {
            Session::set($model . 'website_id', $website_id);
            $this->website_id = $website_id;
        } elseif (Session::get($model . 'website_id')) {
            $this->website_id = Session::get($model . 'website_id');
        } else {
            return json(AjaxReturn(LACK_OF_PARAMETER));
        }
        if (!isApiLegal()) {
            $data['code'] = -2;
            $data['message'] = '接口签名错误';
            echo json_encode($data, JSON_UNESCAPED_UNICODE);
            exit;
        }
        
        $this->initInfo();
        $this->store_id = Session::get($model . 'store_id');
        $this->checkStore();
        $this->upload_avator = 'upload/' . $this->website_id . '/avator/';
        $config = new WebConfig();
        $this->upload_type = $config->getUploadType();
    }
    
    public function initInfo()
    {
        $store = new storeServer();
        $this->assistantId = $store->getAssistantId();
        if (empty($this->assistantId)) {
            echo json_encode(['code' => LOGIN_EXPIRE, 'message' => '登录信息已过期，请重新登陆'], JSON_UNESCAPED_UNICODE);exit;
        }
    }
    public function checkStore()
    {
        $action = $_SERVER['REQUEST_URI'];
        if (empty($this->store_id) && !strstr($action,'storeList') && !strstr($action,'selectStore') && !strstr($action,'getOrderListByCode') && !strstr($action,'consumerCardDetail')) {
            echo json_encode(['code' => CHOOSE_STORE, 'message' => '请选择门店'.$this->store_id], JSON_UNESCAPED_UNICODE);exit;
        }
    }
    
    /*
     * 店员端根据订单id核销订单
     */
    public function pickupOrder()
    {
        $order_id = request()->post("order_id", 0);
        if(!$order_id){
            return json(AjaxReturn(LACK_OF_PARAMETER));
        }
        $storeServer = new storeServer();
        $result = $storeServer->pickupOrder($order_id);
        if($result <= 0){
            return json(AjaxReturn($result));
        }
        return json(['code' => 1, 'message' => '操作成功']);
    }
    /*
     * 店员端根据核销码获取订单信息
     */
    public function getOrderListByCode()
    {
        $code = request()->post("code", 0);
        if(!$code){
            return json(AjaxReturn(LACK_OF_PARAMETER));
        }
        $condition['is_deleted'] = 0; // 未删除订单
        $condition['website_id'] = $this->website_id;
        $condition['shop_id'] = $this->instance_id;
        $condition['verification_code'] = $code;
        $order_service = new OrderService();
        $storeServer = new storeServer();
        $condition['wapstore'] = 1;
        $list = $order_service->getOrderList(1, 0, $condition, 'create_time DESC');
        if(!$list['data']){
            return json([
                'code' => -1,
                'message' => '订单不存在',
            ]);
        }
        $order = $list['data'][0];
        $store_id = $order['store_id'];
        $storeInfo = $storeServer->storeDetail($store_id);
        if(!$storeServer->checkStore($store_id, $this->assistantId)){//店员是否有权限管理该门店订单
            return json([
                'code' => -1,
                'message' => '该码为' . $storeInfo['store_name'] . '核销码，你无法操作，请提示会员到对应门店进行核销。',
            ]);
        }
        if(!$this->store_id || $this->store_id != $store_id){//登陆未选择门店或者所选门店不一致引导店员重新选择门店
            return json([
                'code' => 0,
                'message' => '获取成功',
                'data' => [
                    'store_id' => $store_id,
                    'prompt' => '该码为' . $storeInfo['store_name'] . '核销码，是否切换门店进行核销？'
                ]
            ]);
        }
        $order_info = [];
        $order_info['order_id'] = $order['order_id'];
        $order_info['order_no'] = $order['order_no'];
        $order_info['out_order_no'] = $order['out_trade_no'];
        $order_info['shop_id'] = $order['shop_id'];
        $order_info['shop_name'] = $order['shop_name'] ?: '自营店';
        $order_info['order_money'] = $order['order_money'];
        $order_info['order_status'] = $order['order_status'];
        $order_info['status_name'] = $order['status_name'];
        $order_info['pay_type_name'] = $order['pay_type_name'];
        $order_info['is_evaluate'] = $order['is_evaluate'];
        $order_info['verification_code'] = $order['verification_code'];
        $order_info['verification_qrcode'] = __IMG($order['verification_qrcode']);
        $order_info['member_operation'] = array_merge($order['member_operation'], [['no' => 'detail', 'name' => '订单详情']]);
        $order_info['promotion_status'] = ($order['promotion_money'] + $order['coupon_money'] > 0) ?: false;

        foreach ($order['order_item_list'] as $key_sku => $item) {
            $order_info['order_item_list'][$key_sku]['order_goods_id'] = $item['order_goods_id'];
            $order_info['order_item_list'][$key_sku]['goods_id'] = $item['goods_id'];
            $order_info['order_item_list'][$key_sku]['sku_id'] = $item['sku_id'];
            $order_info['order_item_list'][$key_sku]['goods_name'] = $item['goods_name'];
            $order_info['order_item_list'][$key_sku]['price'] = $item['price'];
            $order_info['order_item_list'][$key_sku]['num'] = $item['num'];
            $order_info['order_item_list'][$key_sku]['pic_cover'] = getApiSrc($item['picture']['pic_cover']);
            $order_info['order_item_list'][$key_sku]['spec'] = $item['spec'];
            $order_info['order_item_list'][$key_sku]['status_name'] = $item['status_name'];
            $order_info['order_item_list'][$key_sku]['refund_status'] = $item['refund_status'];
        }

        // 当订单需要进行整单售后时，这个字段取订单商品第一个商品的售后状态（目前正确情况，所有商品的refund_status一样），用于判断整单售后操作
        $order_info['order_refund_status'] = reset($order_info['order_item_list'])['refund_status'];

        

        return json([
            'code' => 1,
            'message' => '获取成功',
            'data' => [
                'order_list' => $order_info,
            ]
        ]);
    }
    
    /*
     * 店员端获取门店订单
     */
    public function getStoreOrderList()
    {
        $page_index = request()->post('page_index', 1);
        $page_size = request()->post('page_size') ?: PAGESIZE;
        $order_status = request()->post('order_status');
        $search_text = request()->post('search_text');
        $condition['is_deleted'] = 0; // 未删除订单
        $condition['website_id'] = $this->website_id;
        $condition['shop_id'] = $this->instance_id;
        $condition['store_id|card_store_id'] = $this->store_id;
        $condition['shipping_type'] = 2;
        if (is_numeric($search_text)){
            $condition['order_no'] = ['LIKE', '%' . $search_text . '%'];
        } elseif(!empty($search_text)) {
            $condition['goods_name'] = ['LIKE', '%' . $search_text . '%'];
        }
        if ($order_status != '') {
            // $order_status 1 待提货
            if ($order_status == 1) {
                // 订单状态为待发货实际为已经支付未完成还未发货的订单
                $condition['shipping_status'] = 0; // 0 待提货
                $condition['pay_status'] = 2; // 2 已支付
                $condition['order_status'][] = ['neq', 4]; // 4 已完成
                $condition['order_status'][] = ['neq', 5]; // 5 关闭订单
                $condition['order_status'][] = ['neq', -1]; // -1 售后订单
            } else {
                $condition['order_status'] = $order_status;
            }
        }else{
            $condition['order_status'][] = ['neq', 5];
            $condition['order_status'][] = ['neq', -1];
        }
        $order_service = new OrderService();
        $condition['wapstore'] = 1;
        $list = $order_service->getOrderList($page_index, $page_size, $condition, 'create_time DESC');
        $order_list = [];
        foreach ($list['data'] as $k => $order) {
            $order_list[$k]['order_id'] = $order['order_id'];
            $order_list[$k]['order_no'] = $order['order_no'];
            $order_list[$k]['out_order_no'] = $order['out_trade_no'];
            $order_list[$k]['shop_id'] = $order['shop_id'];
            $order_list[$k]['shop_name'] = $order['shop_name'] ?: '自营店';
            $order_list[$k]['order_money'] = $order['order_money'];
            $order_list[$k]['order_status'] = $order['order_status'];
            $order_list[$k]['status_name'] = $order['status_name'];
            $order_list[$k]['pay_type_name'] = $order['pay_type_name'];
            $order_list[$k]['is_evaluate'] = $order['is_evaluate'];
            $order_list[$k]['member_operation'] = array_merge($order['member_operation'], [['no' => 'detail', 'name' => '订单详情']]);
            $order_list[$k]['promotion_status'] = ($order['promotion_money'] + $order['coupon_money'] > 0) ?: false;

            foreach ($order['order_item_list'] as $key_sku => $item) {
                $order_list[$k]['order_item_list'][$key_sku]['order_goods_id'] = $item['order_goods_id'];
                $order_list[$k]['order_item_list'][$key_sku]['goods_id'] = $item['goods_id'];
                $order_list[$k]['order_item_list'][$key_sku]['sku_id'] = $item['sku_id'];
                $order_list[$k]['order_item_list'][$key_sku]['goods_name'] = $item['goods_name'];
                $order_list[$k]['order_item_list'][$key_sku]['price'] = $item['price'];
                $order_list[$k]['order_item_list'][$key_sku]['num'] = $item['num'];
                $order_list[$k]['order_item_list'][$key_sku]['pic_cover'] = getApiSrc($item['picture']['pic_cover']);
                $order_list[$k]['order_item_list'][$key_sku]['spec'] = $item['spec'];
                $order_list[$k]['order_item_list'][$key_sku]['status_name'] = $item['status_name'];
                $order_list[$k]['order_item_list'][$key_sku]['refund_status'] = $item['refund_status'];
            }

            // 当订单需要进行整单售后时，这个字段取订单商品第一个商品的售后状态（目前正确情况，所有商品的refund_status一样），用于判断整单售后操作
            $order_list[$k]['order_refund_status'] = reset($order_list[$k]['order_item_list'])['refund_status'];

        }

        return json([
            'code' => 1,
            'message' => '获取成功',
            'data' => [
                'order_list' => $order_list,
                'page_count' => $list['page_count'],
                'total_count' => $list['total_count']
            ]
        ]);
    }
    /*
     * 店员端获取店员信息
     */
    public function getAssistantInfo()
    {
        $storeServer = new storeServer();
        $assistantInfo = $storeServer->assistantDetail($this->assistantId, $this->store_id);
        if(!$assistantInfo){
            return json(AjaxReturn(0));
        }
        return json(['code' => 1, 'message' => '获取成功', 'data' => $assistantInfo]);
    }
    
    /**
     * 订单详情
     */
    public function orderDetail()
    {
        $order_id = request()->post('order_id');
        if (empty($order_id)) {
            return json(AjaxReturn(LACK_OF_PARAMETER));
        }

        $district_model = new DistrictModel();
        $order_service = new OrderService();
        $order_info = $order_service->getOrderDetail($order_id);

        $order_detail['order_id'] = $order_info['order_id'];
        $order_detail['order_no'] = $order_info['order_no'];
        $order_detail['shop_name'] = $order_info['shop_name'];
        $order_detail['shop_id'] = $order_info['shop_id'];
        $order_detail['order_status'] = $order_info['order_status'];
        $order_detail['payment_type_name'] = $order_info['payment_type_name'];
        $order_detail['promotion_status'] = ($order_info['promotion_money'] + $order_info['coupon_money'] > 0) ?: false;
        $order_detail['order_refund_status'] = reset($order_info['order_goods'])['refund_status'];
        $order_detail['is_evaluate'] = $order_info['is_evaluate'];
        $order_detail['order_money'] = $order_info['order_money'];
        $order_detail['goods_money'] = $order_info['goods_money'];
        $order_detail['shipping_fee'] = $order_info['shipping_money'] - $order_info['promotion_free_shipping'];
        $order_detail['promotion_money'] = 0;

        $address_info = $district_model::get($order_info['receiver_district'], ['city.province']);
        $order_detail['receiver_name'] = $order_info['receiver_name'];
        $order_detail['receiver_mobile'] = $order_info['receiver_mobile'];
        $order_detail['receiver_province'] = $address_info->city->province->province_name;
        $order_detail['receiver_city'] = $address_info->city->city_name;
        $order_detail['receiver_district'] = $address_info->district_name;
        $order_detail['receiver_address'] = $order_info['receiver_address'];
        $order_detail['buyer_message'] = $order_info['buyer_message'];
        $order_detail['card_store_id'] = $order_info['card_store_id'];
        $order_detail['deduction_money'] = $order_info['deduction_money'];
        if($order_info['store_id']){
            $order_detail['store_id'] = $order_info['store_id'];
            $order_detail['verification_code'] = $order_info['verification_code'];
            $order_detail['verification_qrcode'] = __IMG($order_info['verification_qrcode']);
            $order_detail['store_name'] = $order_info['order_pickup']['store_name'];
            $order_detail['store_tel'] = $order_info['order_pickup']['store_tel'];
            $order_detail['receiver_province'] = $order_info['order_pickup']['province_name'];
            $order_detail['receiver_city'] = $order_info['order_pickup']['city_name'];
            $order_detail['receiver_district'] = $order_info['order_pickup']['dictrict_name'];
            $order_detail['receiver_address'] = $order_info['order_pickup']['address'];
        }
        $isGroupSuccess = -1;
        if(getAddons('groupshopping', $order_info['website_id'], $order_info['shop_id'])){
            $group_server = new GroupShopping();
            $isGroupSuccess = $group_server->groupRecordDetail($order_info['group_record_id'])['status'];
        }
        $order_status = OrderService\OrderStatus::getSinceOrderStatusForStore($order_info['order_type'],$isGroupSuccess)[$order_info['order_status']];
        
        $order_detail['member_operation'] = $order_status['member_operation'];

        $order_detail['no_delivery_id_array'] = [];
        foreach ($order_info['order_goods_no_delive'] as $v_goods) {
            $order_detail['no_delivery_id_array'][] = $v_goods['order_goods_id'];
        }

        $goods_packet_list = [];
        foreach ($order_info['goods_packet_list'] as $k => $v_packet) {
            $goods_packet_list[$k]['packet_name'] = $v_packet['packet_name'];
            $goods_packet_list[$k]['shipping_info'] = $v_packet['shipping_info'];
            $goods_packet_list[$k]['order_goods_id_array'] = [];
            foreach ($v_packet['order_goods_list'] as $k_o => $v_goods) {
                $goods_packet_list[$k]['order_goods_id_array'][] = $v_goods['order_goods_id'];
            }
        }
        $order_detail['goods_packet_list'] = $goods_packet_list;

        $order_goods = [];
        foreach ($order_info['order_goods'] as $k => $v) {
            $order_goods[$k]['order_goods_id'] = $v['order_goods_id'];
            $order_goods[$k]['goods_id'] = $v['goods_id'];
            $order_goods[$k]['goods_name'] = $v['goods_name'];
            $order_goods[$k]['sku_id'] = $v['sku_id'];
            $order_goods[$k]['sku_name'] = $v['sku_name'];
            $order_goods[$k]['price'] = $v['price'];
            $order_goods[$k]['num'] = $v['num'];
            $order_goods[$k]['refund_status'] = $v['refund_status'];
            $order_goods[$k]['spec'] = $v['spec'];
            $order_goods[$k]['pic_cover'] = $v['picture_info']['pic_cover'] ? getApiSrc($v['picture_info']['pic_cover']) : '';

            $order_detail['promotion_money'] += round(($v['price'] - $v['actual_price']) * $v['num'], 2) + $v['promotion_free_shipping'];
        }

        $order_detail['order_goods'] = $order_goods;

        return json(['code' => 1,
            'message' => '获取成功',
            'data' => $order_detail
        ]);
    }
    /*
     * 店员列表
     */
    public function assistantList()
    {
        $page_index = request()->post("page_index", 1);
        $page_size = request()->post("page_size", 0);
        $storeServer = new storeServer();
        $condition = array(
            'vsa.website_id' => $this->website_id,
            'vsa.shop_id' => $this->instance_id,
            'vsa.store_id' => $this->store_id,
        );
        $list = $storeServer->assistantList($page_index, $page_size, $condition);
        $list['assistant_list'] = $list['data'];
        unset($list['data']);
        return json(['code' => 1,
            'message' => '获取成功',
            'data' => $list
        ]);
    }
    /*
     * 添加店员时获取岗位列表
     */
    public function getJobsList()
    {
        $storeServer = new storeServer();
        $jobsList = $storeServer->jobsList(1, 0, ['shop_id' => $this->instance_id, 'website_id' => $this->website_id]);
        return json(['code' => 1,
            'message' => '获取成功',
            'data' => $jobsList['data']
        ]);
    }
    
    /*
     * 添加修改店员
     * **/
    public function addOrUpdateAssistant()
    {
        $storeServer = new storeServer();
        $validate_data = [
            'jobs_id' =>  'require',
            'assistant_name' =>  'require',
            'assistant_tel' =>  'require',
        ];
        if(!request()->post('assistant_id',0)){
            $validate_data['password'] = 'require';
        }
        //验证assistant表
        $validate = new Validate($validate_data);
        if( !$validate->check(request()->post()) ){
            return json(['code'=>0,'message'=>$validate->getError()]);
        }
        if(request()->post('assistant_id',0)){
            $ret_val = $storeServer->updateAssistant(request()->post());
        }else{
            $data = request()->post();
            $data['store_id'] = $this->store_id;
            $ret_val = $storeServer->addAssistant($data);
        }
        if($ret_val <= 0){
            return json(AjaxReturn($ret_val));
        }
        return json(['code' => 1, 'message' => '操作成功']);
    }
    /*
     * 销售统计
     */
    
    public function saleStatistics(){
        $date = request()->post('date', '1970-1-1');
        if (empty($date)) {
            return json(AjaxReturn(LACK_OF_PARAMETER));
        }
        $data = array();
        $condition = [
            'website_id' => $this->website_id,
            'shop_id' => $this->instance_id,
            'store_id|card_store_id' => $this->store_id
        ];
        $condition['create_time'][] = [
            '>',
            strtotime($date)
        ];
        $condition['create_time'][] = [
            '<',
            strtotime($date)+86400
        ];
        $condition['order_status'][] = ['>',0];
        $condition['order_status'][] = ['<>',5];
        
        unset($date);
        $orderModel = new VslOrderModel();
        $data['sale_money'] = $orderModel->getSum($condition, 'order_money');
        $data['sale_count'] = $orderModel->getCount($condition);
        $condition['payment_type'] = 2;
        $data['sale_money_alipay'] = $orderModel->getSum($condition, 'order_money');
        $condition['payment_type'] = 1;
        $data['sale_money_wechat'] = $orderModel->getSum($condition, 'order_money');
        $condition['payment_type'] = 5;
        $data['sale_money_balance'] = $orderModel->getSum($condition, 'order_money');
        unset($condition['payment_type']);
        unset($condition['create_time']);
        $condition['sign_time'][] = [
            '>',
            strtotime(date('Y-m-d'.'00:00:00',time()))
        ];
        $condition['sign_time'][] = [
            '<',
            strtotime(date('Y-m-d'.'00:00:00',time()+3600*24))
        ];
        $condition['order_status'] = [['>=',3],['<>',5]];
        $data['finished_count'] = $orderModel->getCount($condition);
        unset($condition['order_status']);
        unset($condition['sign_time']);
        $condition['order_status'] = [['>',0],['<',3]];
        $data['unfinished_count'] = $orderModel->getCount($condition);
        return json(['code' => 1,
            'message' => '获取成功',
            'data' => $data
        ]);
    }
    
    /**
     * 功能说明：文件(图片)上传(存入相册)
     */
    public function uploadImage()
    {

        $file_path = $this->upload_avator;

        // 检测文件夹是否存在，不存在则创建文件夹
        if (!file_exists($file_path)) {
            $mode = intval('0777', 8);
            mkdir($file_path, $mode, true);
        }

        $file_name = $_FILES['file']['name']; // 文件原名
        $temp_file_name = $_FILES['file']['tmp_name']; //临时名称
        $file_size = $_FILES['file']['size']; // 文件大小
        $file_type = $_FILES['file']['type']; // 文件类型

        if ($file_size == 0) {
            $this->return['message'] = '文件大小为0MB';
            return $this->ajaxFileReturn();
        }

        // 验证文件
        if (!$this->validationFile($file_type,$file_size)) {
            return $this->ajaxFileReturn();
        }
        $file_name_explode = explode('.', $file_name); // 图片名称
        $suffix = count($file_name_explode) - 1;
        $ext = '.' . $file_name_explode[$suffix]; // 获取后缀名
        $new_file_name = time() . mt_rand(1000, 9999) . $ext; // 重新命名文件 ,mt_rand防止上传多张时重命名为同一名称

        $ok = $this->moveUploadFile($temp_file_name, $file_path . $new_file_name);
        if ($ok['code']) {
            $this->return['code'] = 1;
            $this->return['data'] = ['src' => getApiSrc($ok['path'])];
            $this->return['message'] = '上传成功';

            $condition['assistant_id'] = $this->assistantId;
            $condition['website_id'] = $this->website_id;
            $data['assistant_headimg'] = $ok['path'];
            $storeServer = new storeServer();
            $storeServer->updateAssistantFiled($data, $condition);
            
            //删除本地的图片
            if($this->upload_type == 2){
                @unlink($file_path . $new_file_name);
            }
        } else {
            // 强制将文件后缀改掉，文件流不同会导致上传文件失败
            $this->return['message'] = '请检查您的上传参数配置或上传的文件是否有误';
        }
        return $this->ajaxFileReturn();
    }
    
    /**
     *
     * @param unknown $this ->file_path
     *            文件路径
     * @param unknown $this ->file_size
     *            文件大小
     * @param unknown $this ->file_type
     *            文件类型
     * @return string|unknown|number|\think\false
     */
    private function validationFile($file_type,$file_size)
    {
        if ($file_type != 'image/gif' && $file_type != 'image/png' && $file_type != 'image/jpeg' && $file_size > 3000000) {
            $this->return['message'] = '文件上传失败,请检查您上传的文件类型,文件大小不能超过3MB';
            return false;
        }
        return true;
    }
    
    /**
     * 原图上传
     *
     * @param unknown $file
     * @param string $destination
     */
    public function moveUploadFile($file, $destination)
    {
        $ok = @move_uploaded_file($file, $destination);
        $result = [
            'code' => $ok,
            'path' => $destination,
            'domain' => '',
            'bucket' => ''
        ];
        if($ok){
            if ($this->upload_type == 2) {
                $alioss = new AliOss();
                $result = $alioss->setAliOssUplaod($destination, $destination);
                @unlink($_FILES['file_upload']);
            }
        }
        return $result;
    }
    /**
     * 上传文件后，ajax返回信息
     *
     *
     * @param array $return
     */
    private function ajaxFileReturn()
    {
        if (empty($this->return['code']) || null == $this->return['code'] || '' == $this->return['code']) {
            $this->return['code'] = -1; // 错误码
        }

        if (empty($this->return['message']) || null == $this->return['message'] || '' == $this->return['message']) {
            $this->return['message'] = ''; // 消息
        }

        if (empty($this->return['data']) || null == $this->return['data'] || '' == $this->return['data']) {
            $this->return['data'] = ''; // 数据
        }
        return json($this->return);
    }
    /*
     * 店员端获取所管理的门店列表
     */
    public function storeList()
    {
        $page_index = request()->post("page_index", 1);
        $page_size = request()->post("page_size", 0);
        $storeServer = new storeServer();
        $list = $storeServer->storeListByAssistantId($this->assistantId,$page_index,$page_size);
        if(!$list['data']){
            return json(AjaxReturn(0));
        }
        $list['store_list'] = $list['data'];
        unset($list['data']);
        return json(['code' => 1,
            'message' => '获取成功',
            'data' => $list
        ]);
    }
    /*
     * 店员端选择了门店
     */
    public function selectStore()
    {
        $store_id = request()->post("store_id", 0);
        if (!$store_id) {
            return json(['code' => 0,
                'message' => '参数错误，请重试'
            ]);
        }
        $storeServer = new storeServer();
        $checkStore = $storeServer->checkStore($store_id, $this->assistantId);
        if(!$checkStore){
            return json(['code' => 0,
                'message' => '选择门店失败，请重新选择门店'
            ]);
        }
        $base = new BaseService();
        $model = $base->getRequestModel();
        Session::set($model . 'store_id', $store_id);
        $this->store_id = $store_id;
        return json(['code' => 1,
            'message' => '操作成功'
        ]);
    }
    /*
     * 修改密码验证密码
     */
    public function checkPassword()
    {
        $password = request()->post('password');
        if (empty($password)) {
            return json(AjaxReturn(LACK_OF_PARAMETER));
        }
        $storeModel = new VslStoreAssistantModel();
        $condition['website_id'] = $this->website_id;
        $condition['assistant_id'] = $this->assistantId;
        $encryptionPw = md5($password);
        $result = $storeModel->getInfo($condition, 'password');
        if($result['password'] != $encryptionPw){
            return json(['code' => -1, 'message' => '密码不正确']);
        }
        return json(['code' => 1, 'message' => '验证通过']);
        
    }
    /*
     * 修改密码
     */
    public function updatePassword()
    {
        $password = request()->post('password');
        if (empty($password)) {
            return json(AjaxReturn(LACK_OF_PARAMETER));
        }
        $storeServer = new storeServer();
        $condition['website_id'] = $this->website_id;
        $condition['assistant_id'] = $this->assistantId;
        $data['password'] = md5($password);

        $result = $storeServer->updateAssistantFiled($data, $condition);
        if ($result) {
            return json(['code' => 1, 'message' => '密码修改成功']);
        } else {
            return json(['code' => -1, 'message' => '密码修改失败']);
        }
    }
    
    /**
     * 礼品券详情
     */
    public function userGiftvoucherInfo()
    {
        $gift_voucher_code = input('gift_voucher_code');
        $VoucherServer = new VoucherServer();
        $info = $VoucherServer->getUserGiftvoucherInfo(0,$gift_voucher_code,$this->instance_id);
        if($info){
            if($info['shop_id']==$this->instance_id){
                $data['code'] = 1;
                $data['message'] = "获取成功";
                $data['data'] = $info;
            }else{
                $data['code'] = -1;
                $data['message'] = "该二维码不是本店的核销码，无法核销。";
                $data['data'] = $info;
            }
        }else{
            $data['code'] = -1;
            $data['message'] = "获取失败";
        }
        return json($data);
    }
    /**
     * 礼品券核销
     */
    public function giftvoucherUse()
    {
        $gift_voucher_code = input('code');
        $VoucherServer = new VoucherServer();
        $result = $VoucherServer->getUserUse($gift_voucher_code,$this->instance_id);
        if($result){
            $this->addUserLog('使用礼品券', $result);
        }
        return json(AjaxReturn($result));
    }
    
    /**
     * 消费卡详情
     */
    public function consumerCardDetail()
    {
        $card_code = input('card_code');
        $member_card = new MemberCard();
        $info = $member_card->getCardDetail(0,$card_code);
        if($info){
            if($info['store_id'] == $this->store_id){
                $data['code'] = 1;
                $data['message'] = "获取成功";
                $data['data'] = $info;
            }else{
                $storeServer = new storeServer();
                $checkStore = $storeServer->checkStore($info['store_id'], $this->assistantId);
                if(!$checkStore){
                    $data['code'] = -1;
                    $data['message'] = "该码为".$info['store_name']."核销码，你无法操作，请提示会员到对应门店进行核销。";
                }else{
                    $data['code'] = 0;
                    $data['message'] = "获取成功";
                    $data['data']['store_id'] = $info['store_id'];
                    $data['data']['prompt'] = "该码为".$info['store_name']."核销码，是否切换门店进行核销？";
                }
            }
        }else{
            $data['code'] = -1;
            $data['message'] = "获取失败";
        }
        return json($data);
    }
    /**
     * 消费卡核销
     */
    public function consumerCardUse()
    {
        $card_code = input('code');
        $member_card = new MemberCard();
        $result = $member_card->getCardUse($card_code,$this->store_id);
        return json(AjaxReturn($result));
    }
    
    /*
     * 微信分享接口
     */
    public function share()
    {
        $weixin = new WchatOauth($this->website_id);
        $url = request()->post('url', '');
        $wx_share = $weixin->shareWx(urldecode($url));
        return json(['code' => 1, 'message' => '成功获取', 'data' => $wx_share]);
    }
}
